package blocos;

import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import blocos.BlockGUI;

public class BlockListener implements MouseListener, MouseMotionListener{
	BlockGUI block = null;
	BlockManager manager;
	boolean action=false;
	int preX;
	int preY;
	
	@Override
	public void mouseDragged(MouseEvent e) {
		
		if((action)&&(block!=null)){
			block.setPosition(preX+e.getX(), preY+e.getY());
			block.setBackground(Color.red);
			block.repaint();
			block.revalidate();
		}
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	public BlockListener(BlockManager manager){
		
		this.manager = manager;
	}
	public boolean isInsideBlock(MouseEvent e){
		if((e.getX()+10>=block.x)&&(e.getX()<=block.x+block.width)&&(e.getY()+10>=block.y)&&(e.getY()<=block.y+block.height))
			return true;
		else
			return false;
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		
		BlockGUI b = manager.selectedBlock(e.getX(), e.getY());
		if(b!=null){
			manager.toTheEnd(b);
			this.block = b;
			block.detachAll();
			action = true;
			preX = block.x - e.getX();
		    preY = block.y - e.getY();
			block.setPosition(preX+e.getX(), preY+e.getY());
			
		}
		
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		if(block!=null){
			if(block.x<0) block.x = 0;
			if(block.y<0) block.y = 0;
			manager.checkAttach(block);
			block.repaint();
			block.revalidate();
			action = false;
			block = null;
			manager.updateBlocks();
		}
		
		
	}
}
